package com.hengxinguotong.zhihuichengjian.ui;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ScrollView;

import com.github.mikephil.charting.charts.BarChart;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.StatisticsBean;
import com.hengxinguotong.zhihuichengjian.bean.StatisticsBeanRes;
import com.hengxinguotong.zhihuichengjian.utils.ColorUtils;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshScrollView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * @CopyRight 恒信国通信息科技
 * @Author wulei
 * @Date 2018/3/29
 * 统计报表页
 * 菜单编号1200
 */

public class StatisticReportActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.secury_line)
    LineChartView securyLine;
    @BindView(R.id.quality_line)
    LineChartView qualityLine;
    @BindView(R.id.person_column)
    ColumnChartView personColumn;
    @BindView(R.id.attend_column)
    ColumnChartView attendColumn;
    @BindView(R.id.date_tv)
    HXTextView dateTv;
    @BindView(R.id.refresh_scroll)
    PullToRefreshScrollView refreshScroll;
    @BindView(R.id.bar_chart)
    BarChart barChart;

    private String constructionId;
    private int year = 0;
    private int monthOfYear = 0;
    private int dayOfMonth = 0;
    private String pTime;
    private Handler handler = new Handler();
    private List<PointValue> securityPoints, qualityPoints ;//图点坐标
    private List<PointValue> securityCorrectives, qualityCorrectives ;//图整改
    private List<AxisValue> securityXlables, qualityXlables, personXlables, attendXlables ;//图x轴
    private List<Column> personColumns, attendColumns ;//柱状图柱集合

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistic_reports);
        ButterKnife.bind(this);
        constructionId = SPUtil.getString(this,"constructionid");
        initDate();
        refreshScroll.setMode(PullToRefreshBase.Mode.PULL_DOWN_TO_REFRESH);
        setListener();
        handler.postDelayed(MyRunnable, 500);
    }

    private void initDate(){
        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        monthOfYear = c.get(Calendar.MONTH);
        dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
        if(monthOfYear < 9){
            if(dayOfMonth < 10){
                pTime = year + "-0" + (monthOfYear + 1) + "-0" + dayOfMonth;
            }else{
                pTime = year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth;
            }
        }else{
            if(dayOfMonth < 10){
                pTime = year + "-" + (monthOfYear + 1) + "-0" + dayOfMonth;
            }else{
                pTime = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
            }
        }
        dateTv.setText(pTime);
    }

    private Runnable MyRunnable = new Runnable() {
        @Override
        public void run() {
            refreshScroll.setRefreshing();
        }
    };

    private void setListener(){
        refreshScroll.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                queryInspectionSecurityList(null);
                queryInspectionQualityList(null);
                queryWorkTypePersonQty(null);
                queryAttendanceNumQty(null);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

            }
        });
    }

    private void queryInspectionSecurityList(String alert){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId",  constructionId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/inspection/safety/queryInspectionMonthQtyList/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(refreshScroll.isRefreshing()){
                    refreshScroll.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    StatisticsBeanRes statisticsBeanRes = gson.fromJson(json, StatisticsBeanRes.class);
                    if(statisticsBeanRes.getStatus() == 1){
                        processSecurity(statisticsBeanRes.getValue());
                    }else{
                        showToast(statisticsBeanRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                if(refreshScroll.isRefreshing()){
                    refreshScroll.onRefreshComplete();
                }
                showToast(json);
            }
        });
    }

    private void processSecurity(List<StatisticsBean> statisticsBeanList){
        getSecurityCorrectives(statisticsBeanList);//x轴
        getSecurityPoints(statisticsBeanList);//y轴
        getSecurityXLables(statisticsBeanList);
        initSecurityLineChart();
    }

    /*
     *获取图x轴坐标
     */
    private void getSecurityXLables(List<StatisticsBean> xData){
        securityXlables = new ArrayList<AxisValue>();
        for(int i = 0; i < xData.size(); i++ ){
            StatisticsBean statisticsBean = xData.get(i);
            AxisValue value = new AxisValue(i);//值是在哪显示 i 是指 第i个柱状图
            value.setLabel(statisticsBean.getDate());//设置显示的文本，默认为柱状图的位置
            securityXlables.add(value);
        }
    }

    /**
     * 线性图表的每个点的显示
     */
    private void getSecurityCorrectives(List<StatisticsBean> yData) {
        securityCorrectives = new ArrayList<PointValue>();
        for (int i = 0; i < yData.size(); i++) {
            StatisticsBean statisticsBean = yData.get(i);
            Float f = Float.parseFloat(statisticsBean.getCorrectiveQty());
            securityCorrectives.add(new PointValue(i, f));
        }
    }

    /**
     * 线性图表的每个点的显示
     */
    private void getSecurityPoints(List<StatisticsBean> yData) {
        securityPoints = new ArrayList<PointValue>();
        for (int i = 0; i < yData.size(); i++) {
            StatisticsBean statisticsBean = yData.get(i);
            Float f = Float.parseFloat(statisticsBean.getQty());
            securityPoints.add(new PointValue(i, f));
        }
    }

    //初始化安全数统计曲线图
    private void initSecurityLineChart(){
        List<Line> lines = new ArrayList<Line>();
        Line line = new Line(securityPoints).setColor(Color.parseColor("#fffe7a81"));  ///折线的颜色
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(true);//曲线是否平滑
        line.setStrokeWidth(1);//线条的粗细，默认是3
        line.setFilled(true);//是否填充曲线的面积
        line.setHasLabels(true);///曲线的数据坐标是否加上备注
        line.setHasLabelsOnlyForSelected(false);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示
        lines.add(line);
        line = new Line(securityCorrectives).setColor(Color.parseColor("#ffffa848"));  ///折线的颜色
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(true);//曲线是否平滑
        line.setStrokeWidth(1);//线条的粗细，默认是3
        line.setFilled(true);//是否填充曲线的面积
        line.setHasLabels(true);///曲线的数据坐标是否加上备注
        line.setHasLabelsOnlyForSelected(false);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(false);  //X轴下面坐标轴字体是斜的显示还是直的，true是斜的显示
//	    axisX.setTextColor(Color.WHITE);  //设置字体颜色
        axisX.setTextColor(Color.parseColor("#D6D6D9"));//灰色

//        axisX.setName("未来几天的天气");  //表格名称
        axisX.setTextSize(11);//设置字体大小
        axisX.setMaxLabelChars(5); ////最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisValues.length
        axisX.setValues(securityXlables);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
//	    data.setAxisXTop(axisX); //x 轴在顶部
        axisX.setHasLines(true); //x 轴分割线


        Axis axisY = new Axis();  //Y轴
//        axisY.setName("y轴标注");//y轴标注
        axisY.setTextSize(11);//设置字体大小
//        data.setAxisYLeft(axisY);  //Y轴设置在左边
        //data.setAxisYRight(axisY);  //Y轴设置在右边
        // 设置行为属性，支持缩放、滑动以及平移
        securyLine.setInteractive(true);//是否支持与用户互动
        securyLine.setZoomEnabled(true);//是否支持缩放
        securyLine.setZoomType(ZoomType.HORIZONTAL);  //缩放类型，水平
        securyLine.setMaxZoom((float) 3);//缩放比例
        securyLine.setLineChartData(data);
        securyLine.setVisibility(View.VISIBLE);
        /**注：下面的7，10只是代表一个数字去类比而已
         * 尼玛搞的老子好辛苦！！！见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         * 下面几句可以设置X轴数据的显示个数（x轴0-7个数据），当数据点个数小于（29）的时候，缩小到极致hellochart默认的是所有显示。当数据点个数大于（29）的时候，
         * 若不设置axisX.setMaxLabelChars(int count)这句话,则会自动适配X轴所能显示的尽量合适的数据个数。
         * 若设置axisX.setMaxLabelChars(int count)这句话,
         * 33个数据点测试，若 axisX.setMaxLabelChars(10);里面的10大于v.right= 7; 里面的7，则
         刚开始X轴显示7条数据，然后缩放的时候X轴的个数会保证大于7小于10
         若小于v.right= 7;中的7,反正我感觉是这两句都好像失效了的样子 - -!
         * 并且Y轴是根据数据的大小自动设置Y轴上限
         * 若这儿不设置 v.right= 7; 这句话，则图表刚开始就会尽可能的显示所有数据，交互性太差
         */
        Viewport v = new Viewport(securyLine.getMaximumViewport());
        v.left = 0;
        v.right= 7;
        securyLine.setCurrentViewport(v);
    }

    private void queryInspectionQualityList(String alert){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId",  constructionId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/inspection/quality/queryInspectionMonthQtyList/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(refreshScroll.isRefreshing()){
                    refreshScroll.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    StatisticsBeanRes statisticsBeanRes = gson.fromJson(json, StatisticsBeanRes.class);
                    if(statisticsBeanRes.getStatus() == 1){
                        processQuality(statisticsBeanRes.getValue());
                    }else{
                        showToast(statisticsBeanRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                if(refreshScroll.isRefreshing()){
                    refreshScroll.onRefreshComplete();
                }
                showToast(json);
            }
        });
    }

    private void processQuality(List<StatisticsBean> statisticsBeanList){
        getQualityCorrectives(statisticsBeanList);//x轴
        getQualityPoints(statisticsBeanList);//y轴
        getQualityXLables(statisticsBeanList);
        initQualityLineChart();
    }

    /*
     *获取图x轴坐标
     */
    private void getQualityXLables(List<StatisticsBean> xData){
        qualityXlables = new ArrayList<AxisValue>();
        for(int i = 0; i < xData.size(); i++ ){
            StatisticsBean statisticsBean = xData.get(i);
            AxisValue value = new AxisValue(i);//值是在哪显示 i 是指 第i个柱状图
            value.setLabel(statisticsBean.getDate());//设置显示的文本，默认为柱状图的位置
            qualityXlables.add(value);
        }
    }

    /**
     * 线性图表的每个点的显示
     */
    private void getQualityCorrectives(List<StatisticsBean> yData) {
        qualityCorrectives = new ArrayList<PointValue>();
        for (int i = 0; i < yData.size(); i++) {
            StatisticsBean statisticsBean = yData.get(i);
            Float f = Float.parseFloat(statisticsBean.getCorrectiveQty());
            qualityCorrectives.add(new PointValue(i, f));
        }
    }

    /**
     * 线性图表的每个点的显示
     */
    private void getQualityPoints(List<StatisticsBean> yData) {
        qualityPoints = new ArrayList<PointValue>();
        for (int i = 0; i < yData.size(); i++) {
            StatisticsBean statisticsBean = yData.get(i);
            Float f = Float.parseFloat(statisticsBean.getQty());
            qualityPoints.add(new PointValue(i, f));
        }
    }

    //初始化项目部质量自查数统计曲线图
    private void initQualityLineChart(){
        List<Line> lines = new ArrayList<Line>();
        Line line = new Line(qualityPoints).setColor(Color.parseColor("#ff1278eb"));  ///折线的颜色
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.SQUARE）
        line.setCubic(true);//曲线是否平滑
        line.setStrokeWidth(1);//线条的粗细，默认是3
        line.setFilled(true);//是否填充曲线的面积
        line.setHasLabels(true);///曲线的数据坐标是否加上备注
        line.setHasLabelsOnlyForSelected(false);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示
        lines.add(line);
        line = new Line(qualityCorrectives).setColor(Color.parseColor("#ff71c0ff"));  ///折线的颜色
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.SQUARE）
        line.setCubic(true);//曲线是否平滑
        line.setStrokeWidth(1);//线条的粗细，默认是3
        line.setFilled(true);//是否填充曲线的面积
        line.setHasLabels(false);///曲线的数据坐标是否加上备注
        line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(false);  //X轴下面坐标轴字体是斜的显示还是直的，true是斜的显示
//	    axisX.setTextColor(Color.WHITE);  //设置字体颜色
        axisX.setTextColor(Color.parseColor("#D6D6D9"));//灰色

//        axisX.setName("未来几天的天气");  //表格名称
        axisX.setTextSize(11);//设置字体大小
        axisX.setMaxLabelChars(5); ////最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisValues.length
        axisX.setValues(qualityXlables);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
//	    data.setAxisXTop(axisX); //x 轴在顶部
        axisX.setHasLines(true); //x 轴分割线


        Axis axisY = new Axis();  //Y轴
//        axisY.setName("y轴标注");//y轴标注
        axisY.setTextSize(11);//设置字体大小
//        data.setAxisYLeft(axisY);  //Y轴设置在左边
        //data.setAxisYRight(axisY);  //Y轴设置在右边
        // 设置行为属性，支持缩放、滑动以及平移
        qualityLine.setInteractive(true);//与用户互动
        qualityLine.setZoomType(ZoomType.HORIZONTAL);  //缩放类型，水平
        qualityLine.setMaxZoom((float) 3);//缩放比例
        qualityLine.setLineChartData(data);
        qualityLine.setVisibility(View.VISIBLE);
        /**注：下面的7，10只是代表一个数字去类比而已
         * 尼玛搞的老子好辛苦！！！见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         * 下面几句可以设置X轴数据的显示个数（x轴0-7个数据），当数据点个数小于（29）的时候，缩小到极致hellochart默认的是所有显示。当数据点个数大于（29）的时候，
         * 若不设置axisX.setMaxLabelChars(int count)这句话,则会自动适配X轴所能显示的尽量合适的数据个数。
         * 若设置axisX.setMaxLabelChars(int count)这句话,
         * 33个数据点测试，若 axisX.setMaxLabelChars(10);里面的10大于v.right= 7; 里面的7，则
         刚开始X轴显示7条数据，然后缩放的时候X轴的个数会保证大于7小于10
         若小于v.right= 7;中的7,反正我感觉是这两句都好像失效了的样子 - -!
         * 并且Y轴是根据数据的大小自动设置Y轴上限
         * 若这儿不设置 v.right= 7; 这句话，则图表刚开始就会尽可能的显示所有数据，交互性太差
         */
        Viewport v = new Viewport(qualityLine.getMaximumViewport());
        v.left = 0;
        v.right= 7;
        qualityLine.setCurrentViewport(v);
    }

    private void queryWorkTypePersonQty(String alert){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId",  constructionId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/attendance/queryWorkTypePersonQty/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(refreshScroll.isRefreshing()){
                    refreshScroll.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    StatisticsBeanRes statisticsBeanRes = gson.fromJson(json, StatisticsBeanRes.class);
                    if(statisticsBeanRes.getStatus() == 1){
                        processPerson(statisticsBeanRes.getValue());
                    }else{
                        showToast(statisticsBeanRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                if(refreshScroll.isRefreshing()){
                    refreshScroll.onRefreshComplete();
                }
                showToast(json);
            }
        });
    }

    private void processPerson(List<StatisticsBean> statisticsBeanList){
        getPersonXLables(statisticsBeanList);
        getPersonColumns(statisticsBeanList);
        generatePersonColumn();
    }

    /*
     *获取线形图柱状图x轴坐标
     */
    private void getPersonXLables(List<StatisticsBean> xData){
        personXlables = new ArrayList<AxisValue>();
        for(int i = 0; i < xData.size(); i++ ){
            StatisticsBean statisticsBean = xData.get(i);
            AxisValue value = new AxisValue(i);//值是在哪显示 i 是指 第i个柱状图
            value.setLabel(statisticsBean.getName());//设置显示的文本，默认为柱状图的位置
            personXlables.add(value);
        }
    }

    /*
     *柱状图每个柱的显示
     */
    private void getPersonColumns(List<StatisticsBean> yData){
        personColumns = new ArrayList<Column>();
        int numColumns = yData.size();//柱状图的数量
        int numSubcolumns = 1;//设置每个柱状图显示的颜色数量(每个柱状图显示多少块)
        for(int i = 0; i < numColumns; i++ ){
            List<SubcolumnValue> values = new ArrayList<SubcolumnValue>();
            StatisticsBean statisticsBean = yData.get(i);
            Float f = Float.parseFloat(statisticsBean.getQty());
            for (int j = 0; j < numSubcolumns; ++j) {
                SubcolumnValue value = new SubcolumnValue(f, ColorUtils.nextColor1());//第一个值是数值(值>0 方向朝上，值<0，方向朝下)，第二个值是颜色
                values.add(value);
            }
            Column column = new Column(values);//一个柱状图的实例
            column.setHasLabels(true);//设置是否显示每个柱状图的高度，
            column.setHasLabelsOnlyForSelected(false);//点击的时候是否显示柱状图的高度，和setHasLabels()和用的时候，setHasLabels()失效
            personColumns.add(column);
        }
    }

    //初始化人员统计柱形图
    private void generatePersonColumn() {
        // Column can have many subcolumns, here by default_grey I use 1 subcolumn in each of 8 columns.
        ColumnChartData mColumnChartData = new ColumnChartData();//表格的数据实例
        mColumnChartData.setColumns(personColumns);
        Axis axisX = new Axis();
//       axisX.setInside(true);//是否显示在里面，默认为false
        axisX.setMaxLabelChars(6);
        axisX.setTextSize(10);
        axisX.setValues(personXlables);
        Axis axisY = new Axis().setHasLines(true);
//      axisX.setName("Axis X(涂涂的坐标轴)");//设置X轴的注释
//      axisY.setName("Axis Y");//设置Y轴的注释
        mColumnChartData.setAxisXBottom(axisX);//设置X轴显示的位置
//        mColumnChartData.setAxisYLeft(axisY);//设置Y轴显示的位置
        personColumn.setColumnChartData(mColumnChartData);//为View设置数据
        personColumn.setZoomType(ZoomType.HORIZONTAL);//缩放类型 水平
        personColumn.setMaxZoom((float) 3);//缩放比例

        Viewport v = new Viewport(personColumn.getMaximumViewport());
        v.left = 0;
        v.right= 7;
        personColumn.setCurrentViewport(v);
    }

    private void queryAttendanceNumQty(String alert){
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId",  constructionId);
            jsonObject.put("attendanceDate",  pTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/attendance/queryAttendanceNumQty/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if(refreshScroll.isRefreshing()){
                    refreshScroll.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    StatisticsBeanRes statisticsBeanRes = gson.fromJson(json, StatisticsBeanRes.class);
                    if(statisticsBeanRes.getStatus() == 1){
                        processAttend(statisticsBeanRes.getValue());
                    }else{
                        showToast(statisticsBeanRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                if(refreshScroll.isRefreshing()){
                    refreshScroll.onRefreshComplete();
                }
                showToast(json);
            }
        });
    }

    private void processAttend(List<StatisticsBean> statisticsBeanList){
        getAttendXLables(statisticsBeanList);
        getAttendColumns(statisticsBeanList);
        generateAttendColumn();
    }

    /*
     *获取线形图柱状图x轴坐标
     */
    private void getAttendXLables(List<StatisticsBean> xData){
        attendXlables = new ArrayList<AxisValue>();
        for(int i = 0; i < xData.size(); i++ ){
            StatisticsBean statisticsBean = xData.get(i);
            AxisValue value = new AxisValue(i);//值是在哪显示 i 是指 第i个柱状图
            value.setLabel(statisticsBean.getName());//设置显示的文本，默认为柱状图的位置
            attendXlables.add(value);
        }
    }

    /*
     *柱状图每个柱的显示
     */
    private void getAttendColumns(List<StatisticsBean> yData){
        attendColumns = new ArrayList<Column>();
        int numColumns = yData.size();//柱状图的数量
        int numSubcolumns = 1;//设置每个柱状图显示的颜色数量(每个柱状图显示多少块)
        for(int i = 0; i < numColumns; i++ ){
            List<SubcolumnValue> values = new ArrayList<SubcolumnValue>();
            StatisticsBean statisticsBean = yData.get(i);
            Float f = Float.parseFloat(statisticsBean.getQty());
            for (int j = 0; j < numSubcolumns; ++j) {
                SubcolumnValue value = new SubcolumnValue(f, ColorUtils.nextColor());//第一个值是数值(值>0 方向朝上，值<0，方向朝下)，第二个值是颜色
                values.add(value);
            }
            Column column = new Column(values);//一个柱状图的实例
            column.setHasLabels(true);//设置是否显示每个柱状图的高度，
            column.setHasLabelsOnlyForSelected(false);//点击的时候是否显示柱状图的高度，和setHasLabels()和用的时候，setHasLabels()失效
            attendColumns.add(column);
        }
    }

    //初始化人员统计柱形图
    private void generateAttendColumn() {
        // Column can have many subcolumns, here by default_grey I use 1 subcolumn in each of 8 columns.
        ColumnChartData mColumnChartData = new ColumnChartData();//表格的数据实例
        mColumnChartData.setColumns(attendColumns);
        Axis axisX = new Axis();
//       axisX.setInside(true);//是否显示在里面，默认为false
        axisX.setValues(attendXlables);
        axisX.setMaxLabelChars(6);
        axisX.setTextSize(10);
        Axis axisY = new Axis().setHasLines(true);
//      axisX.setName("Axis X(涂涂的坐标轴)");//设置X轴的注释
//      axisY.setName("Axis Y");//设置Y轴的注释
        mColumnChartData.setAxisXBottom(axisX);//设置X轴显示的位置
//        mColumnChartData.setAxisYLeft(axisY);//设置Y轴显示的位置
        attendColumn.setColumnChartData(mColumnChartData);//为View设置数据
        attendColumn.setZoomType(ZoomType.HORIZONTAL);//缩放类型 水平
        attendColumn.setMaxZoom((float) 3);//缩放比例

        Viewport v = new Viewport(attendColumn.getMaximumViewport());
        v.left = 0;
        v.right= 7;
        attendColumn.setCurrentViewport(v);
    }


    @OnClick({R.id.date_tv, R.id.iv_back})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.date_tv:
                showWheelViewDialog();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    private void showWheelViewDialog() {
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        StatisticReportActivity.this.year = year;
                        StatisticReportActivity.this.monthOfYear = monthOfYear;
                        StatisticReportActivity.this.dayOfMonth = dayOfMonth;
                        if(monthOfYear < 9){
                            if(dayOfMonth < 10){
                                pTime = year + "-0" + (monthOfYear + 1) + "-0" + dayOfMonth;
                            }else{
                                pTime = year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth;
                            }
                        }else{
                            if(dayOfMonth < 10){
                                pTime = year + "-" + (monthOfYear + 1) + "-0" + dayOfMonth;
                            }else{
                                pTime = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                            }
                        }
                        dateTv.setText(pTime);
                        queryAttendanceNumQty("加载中…");
                    }
                },
                year, monthOfYear, dayOfMonth).show();
    }
}
